package com.sxf.rental.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxf.rental.entity.Role;
import com.sxf.rental.entity.User;
import com.sxf.rental.service.IPermissionService;
import com.sxf.rental.service.IRoleService;
import com.sxf.rental.utils.Result;
import io.swagger.models.auth.In;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sxf
 * @since 2025-03-08
 */
@RestController
@RequestMapping("/rental/role")
public class RoleController {
    @Resource
    private IRoleService roleService;

    @Resource
    private IPermissionService permissionService;
    @PostMapping("/{start}/{size}")
    public Result search(@PathVariable Integer start, @PathVariable Integer size, @RequestBody Role role){

        //设置Role中的CreateID 方式一：从前端处理
        //方式二：从SecurityContextHolder中获取当前用户ID,然后设置
        /*Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();*/
        Page<Role> page=new Page<>(start,size);
        return Result.success().setData(roleService.selectList(page,role));
    }
    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:role:add')") //测试按钮权限功能
    public Result save(@RequestBody Role role){
        return roleService.save(role)?Result.success():Result.fail();
    }
    @PutMapping
    public Result update(@RequestBody Role role){
        return roleService.updateById(role)?Result.success():Result.fail();
    }

    @GetMapping("hasUser/{id}")
    public Result hasUser(@PathVariable Integer id){
        return roleService.hasUser(id)?Result.success().setMessage("有"):Result.success().setMessage("无");
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        return roleService.delete(ids)?Result.success():Result.fail();
    }
    //获取菜单树结构 当前角色ID 用户ID
    @GetMapping("/permissionTree")
    public Result selectPermissionTree(Integer userId,Integer roleId){
        return Result.success(permissionService.selectRolePermissionTree(userId,roleId));
    }
    //权限分配

    @GetMapping("/{roleID}/{permissionIds}")
    public Result assignPermission(@PathVariable Integer roleID,@PathVariable String permissionIds){
        List<Integer> permissionIdsList = Arrays.stream(permissionIds.split(",")).map(Integer::parseInt).toList();
        return roleService.assignPermission(roleID,permissionIdsList)?Result.success():Result.fail();
    }

    //获取所有角色不分页
    @GetMapping
    public Result list(){
        return Result.success().setData(roleService.list());
    }

}
